<!-- components/TableSettings.svelte -->
<script lang="ts">
	import { type TableState } from '../store/table-state.svelte';
	import Checkbox from '$lib/components/Form/Checkbox/Checkbox.svelte';
	import Icon from '$lib/components/Basic/Icon/Icon.svelte';
	import { type ColumnConfig } from '../context/table-context';
	import Divider from '$lib/components/Basic/Divider/Divider.svelte';	

	interface Props {
		tableState: TableState;
		size?: 'sm' | 'md' | 'lg';
	}

	let { tableState, size = 'md' }: Props = $props();

	// 获取顶层列进行排序和控制
	// 注意：这里为了简单展示，做的是顶层列的排序。如果需要所有列，逻辑会复杂很多（树形拖拽）。
	// 我们通常只需要控制顶层列顺序，和所有列的显隐。

	// 扁平化的所有列（用于显隐控制）
	// 但是为了支持排序，我们需要操作 rootColumns
	let localRootColumns = $state<ColumnConfig[]>([]);

	// 同步状态
	$effect(() => {
		// 浅拷贝引用，用于列表渲染
		localRootColumns = [...tableState.rootColumns];
	});

	// --- 拖拽逻辑 (HTML5 Native) ---
	let draggingIndex: number | null = $state(null);

	const handleDragStart = (e: DragEvent, index: number) => {
		draggingIndex = index;
		if (e.dataTransfer) {
			e.dataTransfer.effectAllowed = 'move';
			e.dataTransfer.setData('text/plain', index.toString());
		}
	};

	const handleDragOver = (e: DragEvent, index: number) => {
		e.preventDefault(); // 允许放置
		if (draggingIndex === null || draggingIndex === index) return;

		// 简单的交换逻辑：在视图上实时反馈（可选）
		// 真正提交是在 drop
	};

	const handleDrop = (e: DragEvent, targetIndex: number) => {
		e.preventDefault();
		if (draggingIndex === null) return;

		const fromIndex = draggingIndex;
		const toIndex = targetIndex;

		if (fromIndex !== toIndex) {
			// 移动数组元素
			const item = localRootColumns[fromIndex];
			localRootColumns.splice(fromIndex, 1);
			localRootColumns.splice(toIndex, 0, item);

			// 提交给 State
			const newOrderKeys = localRootColumns.map((c) => c.key as string);
			tableState.updateRootColumnOrder(newOrderKeys);
		}
		draggingIndex = null;
	};

	const handleVisibilityChange = (col: ColumnConfig, checked: boolean) => {
		if (checked) {
			tableState.visibleColumns.add(col.key as string);
		} else {
			tableState.visibleColumns.delete(col.key as string);
		}
        tableState.visibleVersion++;
	};
	let allChecked = $derived(tableState.visibleVersion>=0 && tableState.visibleColumns.size === localRootColumns.length);
	let indeterminate = $derived(
		tableState.visibleVersion>=0 && tableState.visibleColumns.size > 0 && tableState.visibleColumns.size < localRootColumns.length
	);
	const handleAllChange = (checked: boolean) => {
		if (checked) {
			localRootColumns.forEach((col) => {
				tableState.visibleColumns.add(col.key as string);
			});
		} else {
			tableState.visibleColumns.clear();
		}
        tableState.visibleVersion++;
	};
</script>

<div
	class="settings-container"
	class:settings-container--small={size === 'sm'}
	class:settings-container--medium={size === 'md'}
	class:settings-container--large={size === 'lg'}
>
	<div class="settings-header">
		<Checkbox
			{size}
			value="all"
			label="全选"
			modelValue={allChecked}
			{indeterminate}
			onchange={(val) => handleAllChange(val as boolean)}
		/>
	</div>
	<Divider style="dashed" margin="8px" />
	<div class="settings-body">
		{#each localRootColumns as col, index (col.key)}
			<div
				class="settings-item"
				draggable="true"
				ondragstart={(e) => handleDragStart(e, index)}
				ondragover={(e) => handleDragOver(e, index)}
				ondrop={(e) => handleDrop(e, index)}
				class:dragging={draggingIndex === index}
				aria-label={`拖动 ${col.title || String(col.key)}`}
				role="listitem"
			>
				<div class="drag-handle">
					<Icon src="symbol/grid" />
				</div>
				<Checkbox
					{size}
					modelValue={tableState.visibleVersion>=0 && tableState.visibleColumns.has(col.key as string)}
					value={col.key}
					label={col.title}
					onchange={(val) => handleVisibilityChange(col, val as boolean)}
				/>
			</div>
		{/each}
	</div>
</div>

<style lang="scss">
	@use '../styles/tableSettings.scss';
</style>
